package net.asfun.jvalog.action;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.asfun.jvalog.domain.Page;
import net.asfun.jvalog.http.RequestUtil;
import net.asfun.jvalog.view.PagerInfo;

public class PageAction extends BaseAction{
	/**
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	public void index(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		int page = RequestUtil.getIntParam(req, "page");
		PagerInfo pager = new PagerInfo();
		pager.setIndex(page);
		this.assign("pages", Page.list(pager));
		this.assign("pager", pager);
		this.render("admin/pages.html", resp);
	}
	
	public void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		this.render("admin/page.html", resp);
	}
	
	public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String title = RequestUtil.getRequiredParam(req, "title");
		String slogan =  RequestUtil.getStringParam(req, "slogan", title);
		String article = RequestUtil.getRequiredParam(req, "article");
		String excerpt = RequestUtil.getStringParam(req, "excerpt");
		String publish = RequestUtil.getStringParam(req, "publish");
		Page page = new Page();
		page.setTitle(title);
		page.setSlogan(slogan);
		page.setArticle(article);
		page.setExcerpt(excerpt);
		page.setDate(new Date());
		if ( publish.length() > 0 ) {
			page.setPublished(true);
		}
		page.save();
		this.feedback("page.add", req, resp);
	}
	
	public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		Long[] ids = RequestUtil.getLongParams(req, "id");
		for(int i=0; i<ids.length; i++) {
			Page.remove(ids[i]);
		}
		this.feedback("page.delete", req, resp);
	}
	
	public void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		Long id = RequestUtil.getLongParam(req, "id");
		String title = RequestUtil.getRequiredParam(req, "title");
		String slogan =  RequestUtil.getStringParam(req, "slogan", title);
		String article = RequestUtil.getStringParam(req, "article");
		String excerpt = RequestUtil.getStringParam(req, "excerpt");
		String publish = RequestUtil.getStringParam(req, "publish");
		Page page = Page.load(id);
		page.setTitle(title);
		page.setSlogan(slogan);
		if ( article.length() > 0 ) {
			page.setArticle(article);
		}
		page.setExcerpt(excerpt);
		if ( publish.length() > 0 ) {
			page.setPublished(true);
		} else {
			page.setPublished(false);
		}
		page.update();
		this.feedback("page.update", req, resp);
	}
	
	public void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		Long id = RequestUtil.getLongParam(req, "id");
		this.assign("page", Page.load(id));
		this.render("admin/page.html", resp);
	}
	
}
